﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ExaminationSys.DataAccess;
using ExaminationSys.DataAccess.Entity;
using ExaminationSys.DataAccess.Repository;
using ExaminationSys.Helper;
using Ext.Net;
using System.IO;

namespace ExaminationSys.View.SystemManage
{
    public partial class DBSubjectQuestionList : System.Web.UI.Page
    {
        private static readonly DBSubjectQuestionService Proxy = ObjectFactory<DBSubjectQuestionService>.Create();
        private static readonly DBSubjectService ProxySubject = ObjectFactory<DBSubjectService>.Create();
        private static readonly DBQuestionService ProxyQuestion = ObjectFactory<DBQuestionService>.Create();

        public string DbSubjectQuestionId { get { return Request.QueryString["id"] != null ? Request.QueryString["id"].ToString() : string.Empty; } }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!X.IsAjaxRequest)
                PageEntity = null;
            if (Request.QueryString["id"] != null)
            {
                string tempid = Request.QueryString["id"].ToString();
                Guid id = new Guid(tempid);
                DBSubject dbsubject = ProxySubject.Get(id);
                lblTitle.Text = dbsubject.Title;
                GridPanelDBSubjectQuestion.Title = "大题_标题:  " + dbsubject.Title;
                lblTitle2.Text = tempid;
                lblStage.Text = dbsubject.Stage;
            }
        }
        protected void Page_Init(object sender, EventArgs e)
        {
            this.DBSubjectQuestionEditWindow.GridStore = this.StoreDBSubjectQuestion;
            this.DBSubjectQuestionSearchWindowS.GridStore = this.StoreDBSubjectQuestion;
        }

        private int pageSize = 20;
        public static PageEntity PageEntity = null;
        protected void StoreDBSubjectQuestion_RefreshData(object sender, StoreReadDataEventArgs e)
        {
            string sqlWhere = " DBQuestionType='小题' and ID in(select distinct DBQuestionID from DBSubjectQuestion where Status<>0 and ";
            sqlWhere += string.Format("DBSubjectID='{0}')", new Guid(lblTitle2.Text));
            int pageIndex = 0;
            if (PageEntity != null)
            {
                sqlWhere = PageEntity.SqlWhere;
                pageIndex = 1;
            }
            else
            {
                sqlWhere += " and Status<>0";
                pageIndex = (e.Start / e.Limit) + 1;

            }

            int totalPage, totalRecord;
            this.StoreDBSubjectQuestion.DataSource = ProxyQuestion.GetListByPageByView(sqlWhere, " OrderIndex ", pageSize, pageIndex,
                                                                   out totalPage, out totalRecord);
            e.Total = totalRecord;

            this.StoreDBSubjectQuestion.DataBind();
        }

        public void SearchFun(PageEntity pageEntity)
        {
            PageEntity = pageEntity;
        }


        protected void Command(object sender, DirectEventArgs e)
        {
            var command = e.ExtraParams["command"];

            var id = e.ExtraParams["Id"];
            if (string.IsNullOrWhiteSpace(id))
            {
                MessageBoxHelper.ShowInfo("获取ID失败");
                return;
            }

            if (command.Equals("edit", StringComparison.OrdinalIgnoreCase))
            {
                ShowDetails(id);
            }
            else
            {
                var entity = Proxy.Get(new Guid(id));
                if (entity != null)
                {
                    entity.Status = 0;
                    var success = Proxy.Update(entity);
                    if (success)
                    {
                        StoreDBSubjectQuestion.Remove(entity.ID);
                        MessageBoxHelper.ShowInfo("删除成功");
                    }
                }
            }
        }

        protected void Add_Click(object sender, DirectEventArgs e)
        {
            this.DBSubjectQuestionEditWindow.SetData(string.Empty, lblTitle2.Text, lblTitle.Text, lblStage.Text);
            this.DBSubjectQuestionEditWindow.Show();
        }

        [DirectMethod]
        public void DoConfirm()
        {
            RowSelectionModel sm = GridPanelDBSubjectQuestion.SelectionModel.Primary as RowSelectionModel;

            if (sm.SelectedRows.Count == 0)
            {
                MessageBoxHelper.ShowWarning("请选择要删除的记录");
                return;
            }
            X.Msg.Confirm("提示", "是否删除选中记录?", new MessageBoxButtonsConfig
            {
                Yes = new MessageBoxButtonConfig
                {
                    Handler = "X.DoDelete()",
                    Text = "是"
                },
                No = new MessageBoxButtonConfig
                {
                    Text = "否"
                }
            }).Show();
        }

        [DirectMethod]
        public void DoDelete()
        {
            RowSelectionModel sm = GridPanelDBSubjectQuestion.SelectionModel.Primary as RowSelectionModel;

            if (sm.SelectedRows.Count == 0)
            {
                MessageBoxHelper.ShowWarning("请选择要删除的记录");
                return;
            }

            List<string> ids = new List<string>();
            foreach (var row in sm.SelectedRows)
            {
                ids.Add(row.RecordID);
            }
            var success = Proxy.Delete(ids);
            if (success)
            {
                ids.ForEach(id => StoreDBSubjectQuestion.Remove(id));

                //删除后，重新生成OrderIndex
                var qustionlist = Proxy.GetQuestionList(new Guid(DbSubjectQuestionId));
                if (qustionlist != null && qustionlist.Count > 0)
                {
                    var templist = qustionlist.OrderBy(o => o.OrderIndex).ToList();
                    for (var i = 0; i < templist.Count; i++)
                    {
                        templist[i].OrderIndex = i + 1;
                        Proxy.Update(templist[i]);
                    }

                }
                StoreDBSubjectQuestion.Reload();
                //MessageBoxHelper.ShowInfo("保存成功");
            }
        }

        protected void BatchDelete_Click(object sender, DirectEventArgs e)
        {
            RowSelectionModel sm = GridPanelDBSubjectQuestion.SelectionModel.Primary as RowSelectionModel;

            if (sm.SelectedRows.Count == 0)
            {
                MessageBoxHelper.ShowWarning("请选择要删除的记录");
                return;
            }

            List<string> ids = new List<string>();
            foreach (var row in sm.SelectedRows)
            {
                ids.Add(row.RecordID);
            }
            var success = Proxy.Delete(ids);
            if (success)
            {
                ids.ForEach(id => StoreDBSubjectQuestion.Remove(id));

                //删除后，重新生成OrderIndex
                var qustionlist = Proxy.GetQuestionList(new Guid(DbSubjectQuestionId));
                if (qustionlist != null && qustionlist.Count > 0)
                {
                    var templist = qustionlist.OrderBy(o => o.OrderIndex).ToList();
                    for (var i = 0; i < templist.Count; i++)
                    {
                        templist[i].OrderIndex = i + 1;
                        Proxy.Update(templist[i]);
                    }

                }
                StoreDBSubjectQuestion.Reload();
                // MessageBoxHelper.ShowInfo("保存成功");
            }
        }
        protected void BatchLock_Click(object sender, DirectEventArgs e)
        {
            RowSelectionModel sm = GridPanelDBSubjectQuestion.SelectionModel.Primary as RowSelectionModel;

            if (sm.SelectedRows.Count == 0)
            {
                MessageBoxHelper.ShowWarning("请选择要锁定的记录");
                return;
            }
            List<string> ids = new List<string>();
            foreach (var row in sm.SelectedRows)
            {
                ids.Add(row.RecordID);
            }
            var success = Proxy.Lock(ids, 1);
            if (success)
            {
                StoreDBSubjectQuestion.Reload();
                //MessageBoxHelper.ShowInfo("保存成功");
            }
        }

        protected void BatchUnLock_Click(object sender, DirectEventArgs e)
        {
            RowSelectionModel sm = GridPanelDBSubjectQuestion.SelectionModel.Primary as RowSelectionModel;

            if (sm.SelectedRows.Count == 0)
            {
                MessageBoxHelper.ShowWarning("请选择要解锁的记录");
                return;
            }
            List<string> ids = new List<string>();
            foreach (var row in sm.SelectedRows)
            {
                ids.Add(row.RecordID);
            }
            var success = Proxy.Lock(ids, 0);
            if (success)
            {
                StoreDBSubjectQuestion.Reload();
                MessageBoxHelper.ShowInfo("保存成功");
            }
        }

        protected void BtnSearch_Click(object sender, DirectEventArgs e)
        {
            this.DBSubjectQuestionSearchWindowS.Show(SearchFun, lblTitle2.Text, lblTitle.Text);
        }

        protected void Back_Click(object sender, DirectEventArgs e)
        {
            Response.Redirect("DBSubjectList.aspx");
        }

        protected void ShowDetails(string id)
        {
            var realId = new Guid(id);
            var result = ProxyQuestion.Get(realId);
            if (result != null)
            {
                DBSubjectQuestionEditWindow.GridStore = StoreDBSubjectQuestion;
                this.DBSubjectQuestionEditWindow.SetData(id, lblTitle2.Text, lblTitle.Text, lblStage.Text);
                this.DBSubjectQuestionEditWindow.Show();
            }
        }

        protected void BtnFind_Click(object sender, DirectEventArgs e)
        {
            var text = SearchText.Text.Trim();
            StringBuilder sqlWhere = new StringBuilder(" Status<>0 and DBQuestionType='小题' ");
            sqlWhere.Append("and ID in(select distinct DBQuestionID from DBSubjectQuestion where Status<>0 and ");
            sqlWhere.Append(string.Format("DBSubjectID='{0}')", new Guid(lblTitle2.Text)));
            if (!string.IsNullOrWhiteSpace(text))
            {
                text = text.SqlSafe();
                StringBuilder sbWhere = new StringBuilder(" and ");
                sbWhere.Append(" (Knowledge like '%{0}%' ");
                sbWhere.Append(" or KeyWord like '%{0}%' ");
                sbWhere.Append(" or QuestionType like '%{0}%' ");
                sbWhere.Append(" or DBQuestionType like '%{0}%' ");
                sbWhere.Append(" or SubjectType like '%{0}%' ");
                sbWhere.Append(" or Challenge like '%{0}%' ");
                sbWhere.Append(" or AttachFile like '%{0}%' ");
                sbWhere.Append(" or Content like '%{0}%') ");
                sqlWhere.Append(string.Format(sbWhere.ToString(), text));
            }
            PageEntity pageEntity = new PageEntity();
            pageEntity.SqlWhere = sqlWhere.ToString();
            SearchFun(pageEntity);
            StoreDBSubjectQuestion.Reload();
        }

        protected void BtnMoveTo_Click(object sender, DirectEventArgs e)
        {
            RowSelectionModel sm = GridPanelDBSubjectQuestion.SelectionModel.Primary as RowSelectionModel;
            List<string> ids = new List<string>();

            int step = Convert.ToInt32(Step.Value);
            if (step == 0)
            {
                MessageBoxHelper.ShowWarning("请填写您想移动的步数，[负数向前移，正数向后移]。");
                return;
            }

            if (sm.SelectedRows.Count == 0)
            {
                MessageBoxHelper.ShowWarning("请选择要移动的题目！");
                return;
            }
            foreach (var row in sm.SelectedRows)
            {
                ids.Add(row.RecordID);
            }

            if (ids.Count > 1)
            {
                MessageBoxHelper.ShowWarning("目前只支持一道题目的移动！");
                return;
            }

            var setResult = Proxy.SetDBSubjectQuestionIndex(new Guid(ids[0]), new Guid(DbSubjectQuestionId), step);

            if (setResult < 0)
            {
                if (step > 0)
                {
                    MessageBoxHelper.ShowWarning("您选择向后移动步数太大！");
                }
                else
                {
                    MessageBoxHelper.ShowWarning("您选择向前移动步数太大！");
                }
                return;
            }

            StoreDBSubjectQuestion.Reload();
        }

        // 显示上传窗体
        public void ImportData_Click(object sender, DirectEventArgs e)
        {
            ImportDataWindow.Show();
        }

        protected void Upload_Click(object sender, DirectEventArgs e)
        {
            string UploadFile = "";
            if (this.UploadFile.HasFile)
            {
                cbSheetName.ClearValue();
                UploadFile = this.UploadFile.PostedFile.FileName.ToString();
                string strFileName = Path.GetExtension(this.UploadFile.PostedFile.FileName).ToUpper();
                //获取文件后缀              
                if (!(strFileName == ".XLS" || strFileName == ".XLSX"))
                {
                    MessageBoxHelper.ShowWarning("文件格式不正确！\r\n只能上传Excel文件");
                    return;
                }

                int FileSize = Int32.Parse(this.UploadFile.PostedFile.ContentLength.ToString());
                if (FileSize > 5 * 1024 * 1024)
                {
                    MessageBoxHelper.ShowWarning("上传文件过大");
                    return;
                }

                var fileNameTmp = Path.GetFileName(this.UploadFile.PostedFile.FileName);
                string fileName = string.Format("{0}_{1}_{2}", Guid.NewGuid(), DateTime.Now.ToString("yyyyMMddHHmm"), fileNameTmp);
                var filePath = string.Format("{0}/DBQuestion", UIHelpers.BasePath);
                string fileFullName = Path.Combine(Server.MapPath(filePath), fileName);

                try
                {
                    this.UploadFile.PostedFile.SaveAs(fileFullName);
                    ExcelHelper.InitCbSheetData(fileFullName, Store_SheetName);
                    hiddenFilePath.Value = fileFullName;
                    X.Msg.Alert("提示信息", "文件上传成功！", String.Format("afterUpload('{0}');", fileName)).Show();
                    return;
                }
                catch (Exception ex)
                {
                    MessageBoxHelper.ShowError("错误提示", ex.Message);
                    //X.Msg.Alert("提示信息", ex.Message).Show();
                    return;
                }
            }
            else
            {
                MessageBoxHelper.ShowWarning("请先选择要上传的文件");
                return;
            }
        }

        protected void BtnSaveImportData_Click(object sender, DirectEventArgs e)
        {
            try
            {
                var fileName = hiddenFilePath.Value;

                #region 验证


                if (string.IsNullOrEmpty(fileName))
                {
                    MessageBoxHelper.ShowWarning("请先上传文件");
                    return;
                }

                #endregion

                var filePathBase = UIHelpers.BasePath;
                var fileFullName = Path.Combine(Server.MapPath(filePathBase + "/DBQuestion"), fileName);
                var sheetName = cbSheetName.SelectedItem.Value;

                if (string.IsNullOrEmpty(sheetName))
                {
                    MessageBoxHelper.ShowWarning("SheetName不能为空");
                    return;
                }

                var addcount = Proxy.LoadColumns(fileFullName, sheetName, new Guid(lblTitle2.Text));
                MessageBoxHelper.ShowInfo(string.Format("保存成功:{0} 条", addcount));
                StoreDBSubjectQuestion.Reload();
                //this.ImportDataWindow.Hide();
                return;

            }
            catch (Exception ex)
            {
                MessageBoxHelper.ShowError("保存失败,msg:" + ex.Message);
                return;
            }
        }
    }
}
